//
//  MahjongRuleSetVC.m
//  Mahjong
//
//  Created by 饶首建 on 17/6/28.
//  Copyright © 2017年 com.ikamobile.com. All rights reserved.
//

#import "MahjongRuleSetVC.h"

#import "MahjongWaitingVC.h"
#import "MahjongMainVC.h"
#import "MahjongLoginVC.h"
#import "MahjongRuleCVC.h"

#import "MahjongMainGameVC.h"

#import "PatternModel.h"

@interface MahjongRuleSetVC ()<UICollectionViewDelegate,UICollectionViewDataSource>

@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (weak, nonatomic) IBOutlet UICollectionView *fanCollectionView;
@property (nonatomic,strong) PatternModel *patternModel;
@property (nonatomic,strong) NSMutableArray *selectedRuleArr;
@property (nonatomic,strong) NSMutableArray *ruleArr;
@property (nonatomic,strong) NSMutableArray *optionalHuArr;
@property (nonatomic,strong) NSMutableArray *selectedOptionalHuArr;

@property (weak, nonatomic) IBOutlet UIView *ceilingView;
@property (weak, nonatomic) IBOutlet UILabel *numLabel;
@property (weak, nonatomic) IBOutlet UIButton *minusBtn;
@property (weak, nonatomic) IBOutlet UIButton *plusBtn;

@property (weak, nonatomic) IBOutlet UIView *baseView;
@property (weak, nonatomic) IBOutlet UIButton *baseMinusBtn;
@property (weak, nonatomic) IBOutlet UIButton *basePlusBtn;
@property (weak, nonatomic) IBOutlet UILabel *baseLabel;

@property (weak, nonatomic) IBOutlet UIButton *sureBtn;
@property (weak, nonatomic) IBOutlet UIButton *backBtn;

@property (nonatomic,assign) NSInteger ceiling;
@property (nonatomic,assign) NSInteger base;

@end

static NSString *kMahjongRuleCVC = @"kMahjongRuleCVC";

@implementation MahjongRuleSetVC

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
//    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(matchCallBack:) name:NOTIFICATION_MATCH_CALLBACK object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(matchBackCallBack:) name:NOTIFICATION_MATCH_BACK_CALLBACK object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(matchChangeSeatCallBack:) name:NOTIFICATION_MATCH_CHANGE_SEAT_CALLBACK object:nil];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [PatternModel loadRuleSuccess:^(id model) {
        _patternModel = model;
        [_ruleArr addObjectsFromArray:_patternModel.ruleArr];
        [_collectionView reloadData];
    } fail:^(NSString *errorStr) {
        [Hud hudText:@"获取可选打法失败" inView:self.view];
    }];
    
    [PatternModel loadPatternDataSuccess:^(id model) {
        PatternModel *pm = model;
        [_optionalHuArr addObjectsFromArray:pm.optionalHuPatternArr];
        [_fanCollectionView reloadData];
    } fail:^(NSString *errorStr) {
        [Hud hudText:@"获取可选番型失败" inView:self.view];
    }];
}

#pragma mark - Notification

- (void)matchChangeSeatCallBack:(NSNotification *)notification{
    UIViewController *vc =self.presentingViewController;
    while (![vc isKindOfClass:[MahjongLoginVC class]]) {
        vc = vc.presentingViewController;
    }
    [vc dismissViewControllerAnimated:YES completion:^{}];
}

- (void)matchCallBack:(NSNotification *)notification{
    NSDictionary *dic = notification.object;
    dic = [NSDictionary recursionResultJson4NullclassToNullstring:dic];
}

- (void)matchBackCallBack:(NSNotification *)notification{
    NSDictionary *dic = notification.object;
    dic = [NSDictionary recursionResultJson4NullclassToNullstring:dic];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initUI];
    _numLabel.text = @"4";
    _ceiling = 4;
    _baseLabel.text = @"1";
    _base = 1;
    _selectedRuleArr = [NSMutableArray new];
    _ruleArr = [NSMutableArray new];
    _optionalHuArr = [NSMutableArray new];
    _selectedOptionalHuArr = [NSMutableArray new];
}

- (void)initUI{
    _ceilingView.layer.borderWidth = 3.f;
    _ceilingView.layer.borderColor = UIColorHex(9b9b9b).CGColor;
    _ceilingView.layer.masksToBounds = YES;
    
    _numLabel.layer.borderWidth = 3.f;
    _numLabel.layer.borderColor = UIColorHex(9b9b9b).CGColor;
    _numLabel.layer.masksToBounds = YES;
    
    _baseView.layer.borderWidth = 3.f;
    _baseView.layer.borderColor = UIColorHex(9b9b9b).CGColor;
    _baseView.layer.masksToBounds = YES;
    
    _baseLabel.layer.borderWidth = 3.f;
    _baseLabel.layer.borderColor = UIColorHex(9b9b9b).CGColor;
    _baseLabel.layer.masksToBounds = YES;
    
    
    [_collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([MahjongRuleCVC class]) bundle:nil] forCellWithReuseIdentifier:kMahjongRuleCVC];
    [_fanCollectionView registerNib:[UINib nibWithNibName:NSStringFromClass([MahjongRuleCVC class]) bundle:nil] forCellWithReuseIdentifier:kMahjongRuleCVC];

    
}
#pragma mark - 底分
- (IBAction)baseMinusAction:(id)sender {
    switch (_base) {
        case 100:
            _base = 50;
            break;
        case 50:
            _base = 20;
            break;
        case 20:
            _base = 10;
            break;
        case 10:
            _base = 5;
            break;
        case 5:
            _base = 2;
            break;
        case 2:
            _base = 1;
            break;
            
        default:
            _base = 100;
            break;
    }
    _baseLabel.text = NSStringFormat(@"%ld",_base);
}

- (IBAction)basePlusAction:(id)sender {
    //1,2,5,10,20,50,100
    switch (_base) {
        case 1:
            _base = 2;
            break;
        case 2:
            _base = 5;
            break;
        case 5:
            _base = 10;
            break;
        case 10:
            _base = 20;
            break;
        case 20:
            _base = 50;
            break;
        case 50:
            _base = 100;
            break;
            
        default:
            _base = 1;
            break;
    }
    _baseLabel.text = NSStringFormat(@"%ld",_base);
}

- (IBAction)backAction:(id)sender {
    NSString *url = NSStringFormat(@"%@/Matches/%@/users/%@/leave",BASE_URL,_matchModel.matchId,[PlayerModel ownerInstance].playerId);
    [HttpUtil sendRequestURL:url method:POST param:@{} success:^(id response) {
        [self dismissViewControllerAnimated:YES completion:^{}];
    } fail:^(NSString *errorStr) {
        [Hud hudText:errorStr inView:self.view];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self dismissViewControllerAnimated:YES completion:^{}];
        });
    }];
}

#pragma mark - 确定
- (IBAction)sureAction:(id)sender {
    NSString *url = NSStringFormat(@"%@/Matches/%@/createSettings",BASE_URL,_matchModel.matchId);
    NSDictionary *param = @{
                            @"base":@(_base),
                            @"ceiling":@(_ceiling),
                            @"rules":_selectedRuleArr,
                            @"optionalPatterns":_selectedOptionalHuArr
                            };
    [HttpUtil sendRequestURL:url method:POST param:param success:^(id response) {
        NSDictionary *dic = response;
        MatchModel *mm = [MatchModel parseDic:dic];
        if (mm.players.count >= 4 && mm.isSeted) {
            MahjongMainGameVC *vc = [[MahjongMainGameVC alloc]init];
            
//            MahjongMainVC *vc = [[MahjongMainVC alloc]init];
            vc.matchModel = mm;
            [self presentViewController:vc animated:YES completion:^{}];
        }else{
            MahjongWaitingVC *vc = [[MahjongWaitingVC alloc]init];
            vc.matchModel = mm;
            [self presentViewController:vc animated:YES completion:^{}];
        }
    } fail:^(NSString *errorStr) {
        [Hud hudText:errorStr inView:self.view];
    }];
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (collectionView == _collectionView) {
        return _ruleArr.count;
    }else{
        return _optionalHuArr.count;
    }
    
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    MahjongRuleCVC *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kMahjongRuleCVC forIndexPath:indexPath];
    if (collectionView == _collectionView) {
        NSString *title = _ruleArr[indexPath.row];
        cell.titleLabel.text = title;
        cell.titleLabel.hidden = NO;
        cell.descLabel.hidden = YES;
        cell.xlchImageView.hidden = YES;
        if ([title isEqualToString:@"血流成河"]) {
            cell.titleLabel.hidden = YES;
            cell.xlchImageView.hidden = NO;
        }
        if ([title isEqualToString:@"自摸加番"]) {
            cell.descLabel.hidden = NO;
        }
    }else{
        NSString *title = _optionalHuArr[indexPath.row];
        cell.titleLabel.text = title;
        cell.titleLabel.hidden = NO;
        cell.descLabel.hidden = YES;
        cell.xlchImageView.hidden = YES;
    }
    return cell;
}
#pragma mark - UICollectionViewDelegate

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    MahjongRuleCVC *cell = (MahjongRuleCVC*)[collectionView cellForItemAtIndexPath:indexPath];
    if (collectionView == _collectionView) {
        NSString *title = _ruleArr[indexPath.row];
        if ([_selectedRuleArr containsObject:title]) {
            [_selectedRuleArr removeObject:title];
            cell.selectImageView.image = UIImageWithName(@"btn_default");
            cell.titleLabel.textColor = UIColorHex(4A4A4A);
        }else{
            [_selectedRuleArr addObject:title];
            cell.selectImageView.image = UIImageWithName(@"btn_selected");
            cell.titleLabel.textColor = UIColorHex(66B5F0);
        }
    }else if (collectionView == _fanCollectionView){
        NSString *title = _optionalHuArr[indexPath.row];
        if ([_selectedOptionalHuArr containsObject:title]) {
            [_selectedOptionalHuArr removeObject:title];
            cell.selectImageView.image = UIImageWithName(@"btn_default");
            cell.titleLabel.textColor = UIColorHex(4A4A4A);
        }else{
            [_selectedOptionalHuArr addObject:title];
            cell.selectImageView.image = UIImageWithName(@"btn_selected");
            cell.titleLabel.textColor = UIColorHex(66B5F0);
        }
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(200,74);
}
//section的内边距
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

//section之间的行距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}
//item之间的间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return (_collectionView.frame.size.width - 4*200)/5;
}

#pragma mark - 限番
- (IBAction)minusAction:(id)sender {
    switch (_ceiling) {
        case 20:
            _ceiling = 6;
            _numLabel.text = NSStringFormat(@"%ld",_ceiling);
            break;
        case 6:
            _ceiling = 5;
            _numLabel.text = NSStringFormat(@"%ld",_ceiling);
            break;
        case 5:
            _ceiling = 4;
            _numLabel.text = NSStringFormat(@"%ld",_ceiling);
            break;
        case 4:
            _ceiling = 3;
            _numLabel.text = NSStringFormat(@"%ld",_ceiling);
            break;
        case 3:
            _ceiling = 2;
            _numLabel.text = NSStringFormat(@"%ld",_ceiling);
            break;
        case 2:
            _ceiling = 1;
            _numLabel.text = NSStringFormat(@"%ld",_ceiling);
            break;
        case 1:
            _ceiling = 20;
            _numLabel.text = @"不限";
            break;
            
        default:
            break;
    }
    
}

- (IBAction)plusAction:(id)sender {
    switch (_ceiling) {
        case 20:
            _ceiling = 1;
            _numLabel.text = NSStringFormat(@"%ld",_ceiling);
            break;
        case 1:
            _ceiling = 2;
            _numLabel.text = NSStringFormat(@"%ld",_ceiling);
            break;
        case 2:
            _ceiling = 3;
            _numLabel.text = NSStringFormat(@"%ld",_ceiling);
            break;
        case 3:
            _ceiling = 4;
            _numLabel.text = NSStringFormat(@"%ld",_ceiling);
            break;
        case 4:
            _ceiling = 5;
            _numLabel.text = NSStringFormat(@"%ld",_ceiling);
            break;
        case 5:
            _ceiling = 6;
            _numLabel.text = NSStringFormat(@"%ld",_ceiling);
            break;
        case 6:
            _ceiling = 20;
            _numLabel.text = @"不限";
            break;
            
        default:
            break;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
